#!/bin/bash

# Development startup script for C4pad Fun Backend

echo "🚀 Starting C4pad Fun Backend Development Environment..."

# Load environment variables
if [ -f .env ]; then
    echo "📋 Loading environment variables..."
    export $(cat .env | grep -v '^#' | xargs)
else
    echo "⚠️  No .env file found, using defaults"
fi

# Check if PostgreSQL is running
echo "🗄️  Checking PostgreSQL connection..."
if ! pg_isready -q; then
    echo "❌ PostgreSQL is not running. Please start PostgreSQL first."
    echo "   - macOS (Homebrew): brew services start postgresql"
    echo "   - Docker: docker run --name postgres -e POSTGRES_PASSWORD=password -p 5432:5432 -d postgres"
    exit 1
fi

# Check if Redis is running (optional)
echo "📦 Checking Redis connection..."
if ! redis-cli ping > /dev/null 2>&1; then
    echo "⚠️  Redis is not running. Some features may not work."
    echo "   - macOS (Homebrew): brew services start redis"
    echo "   - Docker: docker run --name redis -p 6379:6379 -d redis"
fi

# Generate Prisma client if needed
echo "🔄 Generating Prisma client..."
pnpm prisma generate

# Run database migrations
echo "🗄️  Running database migrations..."
if pnpm prisma migrate dev --name init; then
    echo "✅ Database migrations completed"
else
    echo "⚠️  Database migrations failed, but continuing..."
fi

# Start the development server
echo "🚀 Starting development server..."
echo "📊 Health check: http://localhost:${PORT:-7172}/api/health"
echo "📚 API docs: http://localhost:${PORT:-7172}/api/docs"
echo "🔗 WebSocket: ws://localhost:${PORT:-7172}/realtime"

pnpm start:dev
